// cartArray ： [food, food, food]
// food : foodId, foodName, foodCount, foodUnitPrice, foodPicPath
class ShopCartModel {
    constructor(cartArray) {
        this.foodList = new Map();
        this.cartTotalPrice = 0;
        this.foodListSize = 0;

        if (cartArray.length > 0) {
            for (let food of cartArray) {
                let foodId = food.foodId;
                this.foodList.set(foodId, food);

                let price = parseFloat(food.foodCount * food.foodUnitPrice).toFixed(2);
                this.cartTotalPrice += price;
                this.foodListSize++;
                console.log('shopcar: ', cartTotalPrice, foodListSize, price)
            }
        } else {
            this.getCartFromStorage();
        }
    }
    persistCartToStorage() {
        let arrayToStorage = [];
        for (let food of this.foodList.values()) {
            let newFood = {};
            newFood.foodId = food.foodId;
            newFood.foodName = food.foodName;
            newFood.foodCount = parseInt(food.foodCount);
            newFood.foodUnitPrice = parseFloat(food.foodUnitPrice).toFixed(2);
            newFood.foodPicPath = food.foodPicPath;
            arrayToStorage.push(newFood);
        }
        window.sessionStorage.setItem('shopcart', JSON.stringify(arrayToStorage));
        window.sessionStorage.setItem('cartTotalPrice', this.cartTotalPrice);
        window.sessionStorage.setItem('foodListSize', this.foodListSize);
        // sessionStorage.shopcart = JSON.stringify(arrayToStorage);
        // sessionStorage.cartTotalPrice = this.cartTotalPrice;
        // sessionStorage.foodListSize = this.foodListSize;
    }
    getCartFromStorage() {
        let arrayFromStorage;
        if (!(sessionStorage.shopcart)) {
            arrayFromStorage = null;
        } else {
            arrayFromStorage = JSON.parse(sessionStorage.shopcart);
            this.cartTotalPrice = parseFloat(sessionStorage.cartTotalPrice).toFixed(2);
            this.foodListSize = parseInt(sessionStorage.foodListSize).toFixed(2);
            for (let food of arrayFromStorage) {
                let foodId = food.foodId;
                let newFood = {};
                newFood.foodId = food.foodId;
                newFood.foodName = food.foodName;
                newFood.foodCount = parseInt(food.foodCount);
                newFood.foodUnitPrice = parseFloat(food.foodUnitPrice).toFixed(2);
                newFood.foodPicPath = food.foodPicPath;
                this.foodList.set(foodId, newFood);
            }
        }
    }
    emptyFoodList() {
        this.foodList = new Map();
        this.cartTotalPrice = 0;
        this.foodListSize = 0;
        this.persistCartToStorage();
    }
    reConstructor(cartArray) {
        this.foodList = new Map();
        this.cartTotalPrice = 0;
        this.foodListSize = 0;
        for (let food of cartArray) {
            let foodId = food.foodId;
            this.foodList.set(foodId, food);

            let price = food.foodCount * food.foodUnitPrice;
            this.cartTotalPrice += price;
            this.foodListSize++;
        }
    }
    add(foodId, foodName, foodCount, foodUnitPrice, foodPicPath) {
        if (this.foodList.has(foodId)) {
            let food = this.foodList.get(foodId);

            this.cartTotalPrice -= food.foodCount * food.foodUnitPrice;

            food.foodName = foodName;
            food.foodCount++;
            food.foodUnitPrice = foodUnitPrice;
            food.foodPicPath = foodPicPath;

            this.cartTotalPrice += foodCount * foodUnitPrice;
            return food;
        } else {
            let orderFood = {};
            orderFood.foodId = foodId;
            orderFood.foodName = foodName;
            orderFood.foodCount = foodCount;
            orderFood.foodUnitPrice = foodUnitPrice;
            orderFood.foodPicPath = foodPicPath;
            this.foodList.set(foodId, orderFood);

            this.cartTotalPrice += foodCount * foodUnitPrice;
            this.foodListSize++;
            return orderFood;
        }
    }
    delete(foodId) {
        let returnObj = this.foodList.get(foodId);
        this.foodList.delete(foodId);
        return returnObj;
    }
    update(foodId, foodName, foodCount, foodUnitPrice, foodPicPath) {
        let food = this.foodList.get(foodId);
        this.cartTotalPrice -= food.foodCount * food.foodUnitPrice;

        food.foodName = foodName;
        food.foodCount = foodCount;
        food.foodUnitPrice = foodUnitPrice;
        food.foodPicPath = foodPicPath;

        this.cartTotalPrice += foodCount * foodUnitPrice;
        return food;
    }
    updateFoodSubOnce(foodId) {
        let food = this.foodList.get(foodId);
        food.foodCount--;
        this.cartTotalPrice -= food.foodUnitPrice;

        if (food.foodCount == 0) {
            return this.delete(food.foodId);
        }
        return food;
    }
    updateFoodAddOnce(foodId) {
        let food = this.foodList.get(foodId);
        food.foodCount++;
        // this.cartTotalPrice += food.foodUnitPrice;
        this.cartTotalPrice = parseFloat(this.cartTotalPrice) + parseFloat(food.foodUnitPrice);
        if (food.foodCount == 0) {
            return this.delete(food.foodId);
        }
        return food;
    }
    updateFoodCount(foodId, foodCount) {
        let food = this.foodList.get(foodId);
        this.cartTotalPrice -= food.foodUnitPrice * food.foodCount;

        if (foodCount > 0) {
            food.foodCount = foodCount
            this.cartTotalPrice += food.foodUnitPrice * food.foodCount;
            return food;
        } else if (foodCount == 0) {
            return this.delete(foodId);
        } else {
            throw new Error();
        }
    }
    getFoodById(foodId) {
        return this.foodList.get(foodId);
    }
    getFoodList() {
        return this.foodList;
    }
    getFoodListSize() {
        return this.foodListSize;
    }
    getCartTotalPrice() {
        return this.cartTotalPrice;
    }
}
class ShopCartComponent {
    constructor(shopCartModel, shopCartView) {
        this.model = shopCartModel;
        this.view = shopCartView;
        let that = this;

        // 渲染Model
        this.model.getFoodList().forEach((food) => {
            this.view.insertRow(food.foodId, food.foodName, food.foodCount, food.foodCount * food.foodUnitPrice);
        });
        this.view.updateCartTotalPrice(that.model.getCartTotalPrice());

        // 底部添加点击切换事件
        this.view.getJqObjOfFooterPrice().click(() => {
            this.view.toggleShopCart();
        });
        // 下单按钮添加事件
        this.view.getJqObjOfCheckoutBtn().click(() => {
            this.model.persistCartToStorage();
            if(this.model.getFoodListSize() == 0) {
                alert('EMPTY SHOP CAR')
                return;
            }
            // window.location.href = "order";
            location.href = './placeorder.html'
        });
        // 减少数量按钮添加事件
        this.view.getJqObjOfDiv().on("click", ".subCount", function () {
            let foodid = $(this).parent().parent().attr("foodid");

            that.model.updateFoodSubOnce(foodid);

            let food = that.model.getFoodById(foodid);
            if (food == undefined) {
                that.view.deleteRow(foodid);
            } else {
                that.view.updateRow(food.foodId, food.foodName, food.foodCount, food.foodUnitPrice * food.foodCount);
            }
            that.view.updateCartTotalPrice(that.model.getCartTotalPrice());
        });
        // 增加数量按钮添加事件
        this.view.getJqObjOfDiv().on("click", ".addCount", function () {
            let foodid = $(this).parent().parent().attr("foodid");

            console.log("addCount Before " + (that.model.getFoodById(foodid).foodUnitPrice === parseFloat(that.model.getFoodById(foodid).foodUnitPrice)));
            that.model.updateFoodAddOnce(foodid);
            console.log("addCount After  " + (that.model.getFoodById(foodid).foodUnitPrice === parseFloat(that.model.getFoodById(foodid).foodUnitPrice)));

            let food = that.model.getFoodById(foodid);
            that.view.updateRow(food.foodId, food.foodName, food.foodCount, food.foodUnitPrice * food.foodCount);
            that.view.updateCartTotalPrice(that.model.getCartTotalPrice());
        });
        // 数量输入框添加事件
        this.view.getJqObjOfDiv().on("change", ".shop-cartbasket-row-itemquantity-input", function () {
            let foodid = $(this).parent().parent().attr("foodid");
            let foodcount = $(this).val();

            let food = that.model.updateFoodCount(foodid, foodcount);

            that.view.updateRow(food.foodId, food.foodName, food.foodCount, food.foodCount * food.foodUnitPrice);
            that.view.updateCartTotalPrice(that.model.getCartTotalPrice());
        });
        // 清空购物车按钮添加事件
        this.view.getJqObjOfClearBtn().click(() => {
            this.model.emptyFoodList();
            this.view.emptyRows();
            this.view.updateCartTotalPrice(this.model.getCartTotalPrice());
        });
    }
    bindAddFoodBtn(foodId, foodName, foodUnitPrice, foodPicPath) {
        if (this.model.getFoodList().has(foodId)) {
            this.model.updateFoodAddOnce(foodId);
            let food = this.model.getFoodById(foodId);
            this.view.updateRowQuantity(foodId, food.foodCount);
            this.view.updateRowTotal(food.foodCount * food.foodUnitPrice);
            this.view.updateCartTotalPrice(this.model.getCartTotalPrice());
        } else {
            this.model.add(foodId, foodName, 1, foodUnitPrice, foodPicPath);
            let food = this.model.getFoodList().get(foodId);
            this.view.insertRow(food.foodId, food.foodName, food.foodCount, food.foodCount * food.foodUnitPrice);
            this.view.updateCartTotalPrice(this.model.getCartTotalPrice());
        }
    }
}
class ShopCartView {
    constructor(selectorStr) {
        this.jqObj = $(selectorStr);
        this.topPx = -1 * ShopCartView.SINGLE_ROW_HEIGHT;
        this.showStatus = true;

        this.jqObj.addClass("shop-cart-isolate-scope");
        this.jqObj.html(ShopCartView.INIT_HTML);
    }
    insertRow(itemid, itemname, itemquantity, itemtotal) {
        this.topPx -= ShopCartView.SINGLE_ROW_HEIGHT;
        this.showStatus = true;
        $("#shopcart-basket").css({ top: this.topPx });
        $("#shopcart-basket").append(ShopCartView.getRowHTML(itemid, itemname, itemquantity, itemtotal));
    }
    deleteRow(itemid) {
        if ($(".shop-cartbasket-row[foodid=" + itemid + "]").get().length > 0) {
            $(".shop-cartbasket-row[foodid=" + itemid + "]").remove();
            this.topPx += ShopCartView.SINGLE_ROW_HEIGHT;
            $("#shopcart-basket").animate({ top: this.topPx });
            this.showStatus = true;
        }
    }
    emptyRows() {
        this.jqObj.find(".shop-cartbasket-row").remove();
        this.topPx = -1 * ShopCartView.SINGLE_ROW_HEIGHT;
        this.showStatus = false;
        $("#shopcart-basket").animate({ top: this.topPx });
    }
    updateRow(itemid, itemname, itemquantity, itemtotal) {
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemname").text(itemname);
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemquantity-input").attr("value", itemquantity);
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemtotal").text("￥" + itemtotal);
    }
    updateRowName(itemid, itemname) {
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemname").text(itemname);
    }
    updateRowQuantity(itemid, itemquantity) {
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemquantity-input").attr("value", itemquantity);
    }
    updateRowTotal(itemid, itemtotal) {
        $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemtotal").text("￥" + itemtotal);
    }
    getRow(itemid) {
        let row = {};
        row.itemid = itemid;
        row.itemname = $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemname").text();
        row.itemquantity = $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemquantity-input").attr("value");
        row.itemtotal = $(".shop-cartbasket-row[foodid=" + itemid + "]").find(".shop-cartbasket-row-itemtotal").text().substr(1);
        return row;
    }
    updateCartTotalPrice(price) {
        $(".shop-cartfooter-price-text").text(price);
    }
    toggleShopCart() {
        if (this.showStatus == true) {
            this.showStatus = false;
            $("#shopcart-basket").animate({ top: -ShopCartView.SINGLE_ROW_HEIGHT });
        } else {
            this.showStatus = true;
            $("#shopcart-basket").animate({ top: this.topPx });
        }
    }
    showFlyingItem(top, left) {
        let flyingItem = $(ShopCartView.FLYING_ITEM);
        $("body").append(flyingItem);
        flyingItem.css({ "left": left, "top": top });
        let shopCartOffset = $(".shop-cart").offset();
        flyingItem.animate({ "left": shopCartOffset.left, "top": shopCartOffset.top }, "slow", function () {
            flyingItem.remove();
        });
    }
    getJqObjOfDiv() {
        return this.jqObj;
    }
    getJqObjOfFooterPrice() {
        return this.jqObj.find(".shop-cartfooter-price");
    }
    getJqObjOfCheckoutBtn() {
        return this.jqObj.find(".shop-cartfooter-checkout");
    }
    getJqObjOfSubcountBtn() {
        return $(".shop-cartbasket-row-itemquantity-btn.subCount");
    }
    getJqObjOfAddcountBtn() {
        return this.jqObj.find(".shop-cartbasket-row-itemquantity-btn.addCount");
    }
    getJqObjOfInputQuantity() {
        return this.jqObj.find(".shop-cartbasket .shop-cartbasket-row .shop-cartbasket-row-itemquantity .shop-cartbasket-row-itemquantity-input");
    }
    getJqObjOfClearBtn() {
        return this.jqObj.find(".shop-cartbasket-header-row-clearbtn");
    }
}
ShopCartView.getRowHTML = function (itemid, itemname, itemquantity, itemtotal) {
    return ShopCartView.FOOD_ROW_HTML1 + itemid + ShopCartView.FOOD_ROW_HTML2 + itemname + ShopCartView.FOOD_ROW_HTML3 + itemquantity + ShopCartView.FOOD_ROW_HTML4 + itemtotal + ShopCartView.FOOD_ROW_HTML5;
}
ShopCartView.INIT_HTML = "<div class=\"shop-cart\">"
    + "<div class=\"shop-cartbasket\" id=\"shopcart-basket\">"
    + "<div class=\"shop-cartbasket-header\">"
    + "<div class=\"shop-cartbasket-header-row\">"
    + "购物车"
    + "<button type=\"button\" class=\"btn-link btn-xs shop-cartbasket-header-row-clearbtn\">[清空]</button>"
    + "</div>"
    + "</div>"
    + "</div>"
    + "<div class=\"shop-cartfooter\">"
    + "<div class=\"shop-cartfooter-price\">"
    + "<p class=\"shop-cartfooter-price-text\">0</p>"
    + "<p class=\"shop-cartfooter-price-unit\"> 元</p>"
    + "</div>"
    + "<button class=\"shop-cartfooter-checkout\">下单 ></button>"
    + "</div>"
    + "</div>";
ShopCartView.FOOD_ROW_HTML1 = "<div class=\"shop-cartbasket-row\" foodid=\"";
ShopCartView.FOOD_ROW_HTML2 = "\">"
    + "<div class=\"shop-cartbasket-row-itemname\">";
ShopCartView.FOOD_ROW_HTML3 = "</div>"
    + "<div class=\"shop-cartbasket-row-itemquantity\">"
    + "<button class=\"shop-cartbasket-row-itemquantity-btn subCount\">-</button>"
    + "<input class=\"shop-cartbasket-row-itemquantity-input\" value=\"";
ShopCartView.FOOD_ROW_HTML4 = "\"/>"
    + "<button class=\"shop-cartbasket-row-itemquantity-btn addCount\">+</button>"
    + "</div>"
    + "<div class=\"shop-cartbasket-row-itemtotal\">￥";
ShopCartView.FOOD_ROW_HTML5 = "</div>"
    + "</div > ";
ShopCartView.SINGLE_ROW_HEIGHT = 45;
ShopCartView.FLYING_ITEM = "<div class=\"flying-item\" id=\"flying-item\"><span class=\"glyphicon glyphicon-shopping-cart btn-lg\"></span></div>";